package com.tools.pojo.workflow.bo;

import com.tools.pojo.workflow.po.FlowInstance;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Getter
@Setter
@Slf4j
public class StepContext {

    private Long flowInstanceId;

    private String businessKey;

    private String currentStep;

    private Map<String, Object> contextData;

    private Map<String, Object> stepConfig;

    private Integer flowStatus;

    public <T> T getContextData(String key, Class<T> clazz) {
        Object value = contextData.get(key);
        return clazz.isInstance(value) ? clazz.cast(value) : null;
    }

    public void putContextData(String key, Object value) {
        contextData.put(key, value);
    }

    // 新增上下文同步方法
    public void refreshFromFlowInstance(FlowInstance flowInstance) {
        try {
            // 合并流程实例中的最新数据
            Map<String, Object> latestData = flowInstance.parseContextData();
            if (this.contextData == null) {
                this.contextData = new ConcurrentHashMap<>();
            }
            this.contextData.putAll(latestData);

            // 同步流程状态
            this.setCurrentStep(flowInstance.getCurrentNodeCode());
            this.setFlowStatus(flowInstance.getStatus());
        } catch (Exception e) {
            log.error("上下文同步失败，流程实例ID: {}", flowInstance.getId(), e);
        }
    }

}
